package cn.edu.xaut.mybatisers.mall.Interceptor;

import cn.edu.xaut.mybatisers.mall.Exception.ExceptionEntity.AuthorityException;
import cn.edu.xaut.mybatisers.mall.Exception.ExceptionEntity.LoginException;
import cn.edu.xaut.mybatisers.mall.tool.LoginStatus;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.InvalidKeyException;


@Component
public class LoginCheck implements HandlerInterceptor{
    @Autowired
    LoginStatus loginStatus;

    @ApiOperation("验证登录态, 每次请求都验证")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws AuthorityException, LoginException, InvalidKeyException {
        final String token = request.getHeader("token");
        if (token == null || !(loginStatus.checkLoginStatus(token))) {
            throw new LoginException("登录态错误");
        }

        if (request.getRequestURI().contains("admin") && request.getSession().getAttribute("admin_id") == null){
            throw new AuthorityException();
        }

        return true;
    }
}
